//app.js
var qcloud = require('./vendor/wafer2-client-sdk/index')
var config = require('./config')
var util = require('./utils/util.js')

var userInfo = { }
var logged = false


App({
  onLaunch: function () {
    qcloud.setLoginUrl(config.service.loginUrl)
    
    
      if (this.logged) return
      util.showBusy('正在登录')

      var that = this

      // 调用登录接口
      qcloud.login({
        success(result) {
          if (result) {
            util.showSuccess('登录成功')
            that.userInfo = result,
            that.logged = true
            // 首次登录成功后，将用户的openId以及昵称存到缓存(异步操作)
            wx.setStorage('openId', result.openId)
            wx.setStorage('nickName', result.nickName)
            wx.setStorage('avatarUrl', result.avatatUrl)
          } else {
            // 如果不是首次登录，不会返回用户信息，请求用户信息接口获取
            qcloud.request({
              url: config.service.requestUrl,
              login: true,
              success(result) {
              util.showSuccess('登录成功')
              that.userInfo = result.data.data,
              that.logged = true
              console.log(result.data.data)
              // 非首次登录成功后，将用户的openId、昵称以及头像url存到缓存(异步操作)
              wx.setStorage({
                key: 'openId',
                data: that.userInfo.openId,
              })
              wx.setStorage({
                key: 'nickName',
                data: that.userInfo.nickName,
              })
              wx.setStorage({
                key: 'avatarUrl',
                data: that.userInfo.avatarUrl,
              })
   
              wx.getStorage({
                key: 'openId',
                success: function(res) {
                  console.log('用户的openId：' + res.data)
                },
              })
              wx.getStorage({
                key: 'nickName',
                success: function (res) {
                  console.log('用户的昵称：：' + res.data)
                },
              })
              wx.getStorage({
                key: 'avatarUrl',
                success: function (res) {
                  console.log('用户的头像url：' + res.data)
                },
              })

              //使用同步的方式将服务器返回的数据存到缓存中
              // wx.setStorage({'openId', that.userInfo.openId})
              // wx.setStorage('nickName', that.userInfo.nickName)
              // wx.setStorage('avatarUrl', that.userInfo.avatarUrl)
              //console.log('用户的openId：'+ wx.getStorageSync('openId'))
              //console.log('用户的昵称：' + wx.getStorageSync('nickName'))
              //console.log(wx.getStorageSync('avatarUrl'))
            },

            fail(error) {
              util.showModel('请求失败', error)
              console.log('request fail', error)
            }
          })
        }
      },

      fail(error) {
        util.showModel('登录失败', error)
        console.log('登录失败', error)
      }
    })   
  },
})